using AutoMapper;
using Domain.Production_Modules;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.InvoiceTicket.Invoice;
using ReturnValue;
using System.Transactions;

namespace MES.Server.API.Application.Handler.InvoiceTicket.Invoice
{
    public class AddInvoicePaymentCommandHandler : IRequestHandler<AddInvoicePaymentCommand, ApiResult<int>>
    {
        private readonly IRepository<OrderModel> _orderRepo;
        private readonly ILogger<AddInvoicePaymentCommandHandler> _logger;

        public AddInvoicePaymentCommandHandler(
            IRepository<OrderModel> orderRepo,
            ILogger<AddInvoicePaymentCommandHandler> logger)
        {
            _orderRepo = orderRepo;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(AddInvoicePaymentCommand request, CancellationToken cancellationToken)
        {
            // 使用事务确保数据一致性
            using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    // 获取相关订单
                    var order = await _orderRepo.GetValue(request.OrderId);
                    if (order == null)
                    {
                        return new ApiResult<int>().Fail("未找到对应的订单记录!");
                    }

                    // 解析金额
                    if (!int.TryParse(request.InvoiceAmount, out int invoiceAmount))
                    {
                        return new ApiResult<int>().Fail("发票金额格式不正确!");
                    }

                    if (invoiceAmount <= 0)
                    {
                        return new ApiResult<int>().Fail("发票金额必须大于0!");
                    }

                    // 更新订单已付金额
                    order.Tomomeny += invoiceAmount;
                    order.UpdaterPeople = "admin";
                    order.UpdateTime = DateTime.Now;

                    // 保存更改
                    var result = await _orderRepo.UpdateAsync(order);
                    tran.Complete();

                    if (result > 0)
                    {
                        return new ApiResult<int>().Success("添加发票金额成功!", result);
                    }
                    else
                    {
                        return new ApiResult<int>().Fail("添加发票金额失败!");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError($"添加发票金额时发生异常: {ex.Message}");
                    return new ApiResult<int>().Fail($"添加发票金额失败: {ex.Message}");
                }
            }
        }
    }
}
